package com.ruoyi.ruoyiqywechat.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.qy.domain.User;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.utils.CrmebUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ruoyiqywechat.domain.MembershipPlanNew;
import com.ruoyi.ruoyiqywechat.domain.OrderQy;
import com.ruoyi.ruoyiqywechat.domain.UserMembership;
import com.ruoyi.ruoyiqywechat.mapper.MembershipPlanNewMapper;
import com.ruoyi.ruoyiqywechat.mapper.OrderQyMapper;
import com.ruoyi.ruoyiqywechat.mapper.UserMembershipMapper;
import com.ruoyi.ruoyiqywechat.service.PcAppPayService;
import com.ruoyi.ruoyiqywechat.service.UserService;
import com.ruoyi.ruoyiqywechat.wx.pay.config.PayConstants;
import io.jsonwebtoken.Claims;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

@Primary
@Service("pcAppPayServiceImpl")
public class PcAppPayServiceImpl implements PcAppPayService {
    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private UserService userService;

    @Autowired
    private MembershipPlanNewMapper membershipPlanNewMapper;

    @Autowired
    private OrderQyMapper orderQyMapper;
    @Override
    public String createOrderH5orGZH(Long memberId,String orderNum) throws IOException {
        Claims claims = JwtUtils.parseToken(SecurityUtils.getToken());
        String userid = JwtUtils.getUserId(claims);
        if(userid == null)throw new CrmebException("用户不存在!");
        QueryWrapper<OrderQy> orderQyQueryWrapper = new QueryWrapper<>();
        orderQyQueryWrapper.lambda().eq(OrderQy::getOrderNo,orderNum);
        OrderQy storeOrder = orderQyMapper.selectOne(orderQyQueryWrapper);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new CrmebException("订单不存在");
        }
        MembershipPlanNew membershipPlanNew = membershipPlanNewMapper.selectMembershipPlanNewById(memberId);
        if(membershipPlanNew == null){
            throw new RuntimeException("操作错误!");
        }

        Long userId = storeOrder.getUserId();
        User user = userService.getById(userId);
        BigDecimal total = membershipPlanNew.getPrice();
        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi");
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("mchid", PayConstants.MCH_ID)
                .put("appid",PayConstants.H5_APP_ID)
                .put("description", "h5页面下单")
                .put("out_trade_no",storeOrder.getOrderNo())
                .put("notify_url", PayConstants.NOTIFY_URL);
        rootNode.putObject("amount")
                .put("total",total.multiply(new BigDecimal("100")).setScale(0, RoundingMode.DOWN).longValue() )
                .put("currency", "CNY");
        rootNode.putObject("payer")
                .put("openid",user.getMark());
        rootNode.putObject("scene_info")
                .put("payer_client_ip", IpUtils.getIpAddr());
        objectMapper.writeValue(bos, rootNode);
        httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String  bodyAsString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(bodyAsString);
            System.out.println("jsapi:"+jsonObject);
            String string = jsonObject.getString("h5_url");
            return string;
        }catch (Exception e){
           throw new RuntimeException("下单失败");
        }
    }
}
